package models

import (
	"api01/util"
	"errors"
	"github.com/astaxie/beego/orm"
)

type Role struct {
	Id int
	Name string
}

func init()  {
	orm.RegisterModel(new(Role))
}

func GetRoleAll(keyword string, page int, limit int) ([]Role , error) {
	o := orm.NewOrm()
	var roles []Role
	qs := o.QueryTable("role")
	if keyword != "" {
		qs.Filter("name", keyword)
	}
	_, err := qs.Limit(limit, (page-1)*limit).All(&roles)
	if err != nil {
		return roles, errors.New("查询失败")
	}
	return roles , nil
}

func AddRoleOne(role *Role) error {
	o := orm.NewOrm()
	count, _ := o.QueryTable("role").Filter("name", role.Name).Count()
	if count>0 {
		return errors.New("角色名称重复")
	}
	_, err := o.Insert(role)
	if err !=nil {
		util.Log.Error("role Insert err:"+err.Error())
		return errors.New("创建失败")
	}
	return nil
}

func GetRoleById(id int) (Role, error) {
	o := orm.NewOrm()
	role := Role{}
	err := o.QueryTable("role").Filter("id", id).One(&role)
	if err != nil {
		return role, errors.New("数据丢失")
	}
	return role, nil
}

func UpdateRoleById(id int, name string) error {
	o := orm.NewOrm()
	role := new(Role)
	err := o.QueryTable("role").Filter("id", id).One(role)
	if err != nil {
		return errors.New("角色丢失")
	}
	role.Name = name
	_, err = o.Update(role)
	if err != nil {
		return errors.New("角色修改失败")
	}
	return nil
}

func DeleteRoleById(id int) error {
	o := orm.NewOrm()
	role := new(Role)
	err := o.QueryTable("role").Filter("id", id).One(role)
	if err != nil {
		return errors.New("角色丢失")
	}
	_, err = o.Delete(role)
	if err != nil {
		return errors.New("角色删除失败")
	}
	return nil
}